const mongoose = require('mongoose')
const db='mongodb://localhost/douban-trailer'//数据库地址
const glob = require('glob')
const { resolve } = require('path')

mongoose.Promise = global.Promise

exports.initSchemas = () => {
	glob.sync(resolve(__dirname,'./schema', '**/*.js')).forEach(require)
}
exports.connect = () => {
  let maxConnectTimes = 0

  return new Promise((resolve, reject) => {
  	//如果不是生产环境就打印debug
    if (process.env.NODE_ENV !== 'production') {
      mongoose.set('debug', true)
    }
    //连接数据库
    mongoose.connect(db)

    //如果连接失败，重连
    mongoose.connection.on('disconnected', () => {
      maxConnectTimes++

      if (maxConnectTimes < 5) {
        mongoose.connect(db)
      } else {
        throw new Error('数据库挂了吧，快去修吧少年')
      }
    })
    //报错
    mongoose.connection.on('error', err => {
      maxConnectTimes++

      if (maxConnectTimes < 5) {
        mongoose.connect(db)
      } else {
        throw new Error('数据库挂了吧，快去修吧少年')
      }
    })
    //打开数据库
    mongoose.connection.once('open', () => {
    //模拟保存数据的过程	
      // const Dog = mongoose.model('Dog', { name: String })
      // const doga = new Dog({ name: '阿尔法' })

      // doga.save().then(() => {
      //   console.log('wang')
      // })
      resolve()
      console.log('MongoDB Connected successfully!')
    })
  })
}